package com.jxl.interceptor;

import com.alibaba.fastjson.JSON;
import com.jxl.pojo.User;
import com.jxl.utils.ParamUtils;
import com.jxl.utils.WebUtils;
import com.jxl.web.WebResult;
import com.jxl.web.constant.Constant;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 系统拦截器
 * @author 江雪林
 * @create 2021-03-18
 */
public class SysHandlerInterceptor implements HandlerInterceptor {
    private static final Logger log = Logger.getLogger(SysHandlerInterceptor.class);

    /**
     * 访问控制器前拦截请求，即：在 DispatchServlet 分发器，执行分发前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截控制器
        String uri = request.getRequestURI();
        log.info("-> 请求 "+uri+" 访问 <-");
        //获取入参参数名+参数值，封装到 Map容器中
        Map<String,String> paramMap = ParamUtils.getKeyValuesMap(request);
        log.info("-> 请求参数：\n"+paramMap.toString());
        log.info("-> 请求调用处理器："+handler.toString()+" <-");
        //判断访问的控制器是否请求登录，注册处理器
        if(uri.startsWith(request.getContextPath()+"/login") || uri.startsWith(request.getContextPath()+"/register") ||
        uri.startsWith(request.getContextPath()+"/user/login")){
            return true;//放行
        }
        User user = (User) request.getSession().getAttribute(Constant.SESSION_USER);
        if (user != null) {
            log.info("->用户 "+user.getUsername()+"访问 "+uri+" <-");
            return true;
        }
        log.info("-> 请求 "+uri+"被拦截 <-");
        PrintWriter out = response.getWriter();
        WebResult result = new WebResult(Constant.NO_POWER, Constant.VALID_USER_LOGIN);
        WebUtils.response(response,result);
        return false;//拦截跳转
    }

    /**
     * 在 DispatchServlet 分发器，进行下一步视图页面渲染前执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("-> 调用控制器："+handler.toString()+" 进行数据处理 <-");
    }

    /**
     * 在进行视图页面渲染后，响应客户端之前执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(ex!=null){
            log.info("-> 调用控制器："+handler.toString()+"发生异常，异常信息：\n"+ex.getMessage()+" <-");
        }
        log.info("-> 调用控制器："+handler.toString()+"执行完毕 <-");
    }
}
